from fastapi import APIRouter, Request, Query
from sqlalchemy.orm import Session
from typing import List
from fastapi import Depends
from utils.response import success, fail, tableinfo
from utils.database import get_db
from utils.request import PageInfo, QueryWrapper
from app.model import MenuModel
from app.schema import MenuData

menuController = APIRouter()


@menuController.get("/list")
def get_list(filter:str=Query(default='{}'), db=Depends(get_db)):
    where = QueryWrapper.build_query_wrapper(filter)
    rows = MenuModel.get_list(db, where)
    return tableinfo("查询成功", len(rows), rows)

@menuController.get("/tree")
def get_tree(db=Depends(get_db)):
    rows = MenuModel.get_tree(db)
    return success("添加成功", rows)

@menuController.get("/trees")
def get_tree(db=Depends(get_db)):
    rows = MenuModel.get_trees(db)
    return success("添加成功", rows)

@menuController.post("/add")
async def add_data(data: MenuData, db: Session = Depends(get_db)):
    """
    增加角色
    """
    try:
        r = MenuModel.insert(db, data)
        return success("添加成功")
    except Exception as e:
        return fail("添加失败："+str(e))

@menuController.post("/edit")   
async def edit_data(data: MenuData, db: Session = Depends(get_db)):
    """
    修改角色
    """
    try:
        row = data.dict(exclude_unset=True)
        r = MenuModel.edit(db, row)
        return success("修改成功")
    except Exception as e:
        return fail("修改失败："+str(e))
    
@menuController.post("/delete")   
async def delete_data(ids:List[int], db: Session = Depends(get_db)):
    """
    修改角色
    """
    try:
        r = MenuModel.delete(db, ids)
        return success("删除成功")
    except Exception as e:
        return fail("删除失败："+str(e))